/*
 * Copyright 2007 Xplayat, S.L. All rights reserved.
 * Propiedad de Xplayat. 
 */
package es.xpt.ysf.utils;

import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.jboss.security.SecurityAssociation;

import es.xpt.ysf.jaas.YSFPrincipal;
import es.xpt.ysf.view.model.UserBean;


/**
 *  This class is an implementation of the Service Locator pattern. It is
 *  used to looukup resources such as EJBHomes, JMS Destinations, etc.
 */
public class ServiceLocator {

  private InitialContext ic;
  
  public ServiceLocator(UserBean userBean) throws ServiceLocatorException {
	    try {
	    	Properties environmet = DefaultJndiProperties.getJndiProperties();   
		    environmet.put( Context.SECURITY_PRINCIPAL, userBean.getPrincipal());
		    Object credential = SecurityAssociation.getCredential();
		    if ( credential != null )
		    	environmet.put( Context.SECURITY_CREDENTIALS, credential);
		    else 
		    	environmet.put( Context.SECURITY_CREDENTIALS, "");

	        ic = new InitialContext(environmet);
	    } catch (NamingException ne) {
	      throw new ServiceLocatorException(ne);
	    } 
	  }
  
  public ServiceLocator(YSFPrincipal principal,String credential) throws ServiceLocatorException {
	    try {
	    	Properties environmet = DefaultJndiProperties.getJndiProperties();   
		    environmet.put( Context.SECURITY_PRINCIPAL, principal);
		    
		    if ( credential != null )
		    	environmet.put( Context.SECURITY_CREDENTIALS, credential);
		    else 
		    	environmet.put( Context.SECURITY_CREDENTIALS, "");
	        ic = new InitialContext(environmet);
	    } catch (NamingException ne) {
	      throw new ServiceLocatorException(ne);
	    } 
	  }


/**
  * will get the ejb Local home factory.
  * clients need to cast to the type of EJBHome they desire
  *
  * @return the Local EJB Home corresponding to the homeName
  */
  public Object getLocal(JNDINames localName) throws ServiceLocatorException {
    try {
      return ic.lookup(localName.getValue());
    } catch (NamingException ne) {
      throw new ServiceLocatorException(ne);
    }
  }


}